package logic

import (
	"beike/cache"
	"beike/models"
	"context"
	"fmt"

	"beike/houserpc/houserpc"
	"beike/houserpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type ForgetLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewForgetLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ForgetLogic {
	return &ForgetLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *ForgetLogic) Forget(in *houserpc.ForgetRequest) (*houserpc.ForgetResponse, error) {
	// todo: add your logic here and delete this line

	var user models.User

	models.DB.Debug().Where("mobile = ?", in.Mobile).Find(&user)
	if user.ID == 0 {
		return nil, fmt.Errorf("当前手机号未注册")
	}

	result, _ := cache.Rdb.Get(l.ctx, "sendSms"+in.Mobile).Result()
	if result == "" {
		return nil, fmt.Errorf("你还未发送短信")
	}

	if result != in.SendSms {
		return nil, fmt.Errorf("短信验证码错误")
	}

	if in.Password != in.NewPassword {
		return nil, fmt.Errorf("两次密码不同，请重新输入")
	}

	if in.Password == user.Password {
		return nil, fmt.Errorf("当前密码与旧密码一致，请重新输入")
	}

	user.Password = in.Password

	models.DB.Debug().Updates(&user)

	return &houserpc.ForgetResponse{
		UserId: int64(user.ID),
	}, nil
}
